#include "UdpServer.hpp"
#include <cstdio>
#include <memory>
using namespace std;
void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n"
              << std::endl;
}
string Handler(const string &str, const string &clientip, uint16_t clientport)
{
    cout << "[" << clientip << ":" << clientport << "]#" << str << endl;
    string result = "server send a message:";
    result += str;
    return result;
}

string ExcausetCommand(const string &str)
{
    cout << "client send a message:" << str << endl;
    FILE *fp = popen(str.c_str(), "r"); // popen调用fork创建一个子进程用来执行command命令，如果typo=="r",做创建一个管道连接标准输出
    if (NULL == fp)
    {
        perror("popen fail");
        exit(0);
    }
    char buffer[4096];
    string result;
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == NULL)
            break;
        result += ok;
    }

    return result;
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);

    std::unique_ptr<udpServer> svr(new udpServer(port));
    svr->Init();
    svr->Run(Handler);

    return 0;
}

// int main(int argc, char *argv[])
// {
//     if (argc != 2)
//     {
//         Usage(argv[0]);
//         exit(0);
//     }
//     uint16_t port = std::stoi(argv[1]);

//     UdpServer *svr = new UdpServer(port);
//     svr->Init();
//     svr->Run();

//     delete svr;
//     return 0;
// }